/**
 * Created by xiaobozhu on 2016/12/18.
 */

// Load JSON study information for each study
function loadStudy(studyViewer, viewportModel, studyId) {



    // Get the JSON data for the selected studyId
    //test 、、back     $.getJSON('studies/' + studyId, function(data) {
    //var studyurl ='http://120.25.244.147:8081/test/studies/' + studyId;
    var myurl = GetHosturl();
    var studyurl = myurl + 'test/studies/' + studyId;
    //console.log(studyurl);
    var doFunc2 = function(d) {
        console.log(d);
        var data = d['patient']['studies'][0]
        console.log(data);
        var imageViewer = new ImageViewer(studyViewer, viewportModel);
        imageViewer.setLayout('1x1'); // default layout

        function initViewports() {
            imageViewer.forEachElement(function(el) {
                console.log($(el))
                jarvisframe.enable(el);
                if($(el).droppable) {
                    $(el).droppable({
                        drop: function (evt, ui) {
                            var fromStack = $(ui.draggable.context).data('stack'), toItem = $(this).data('index');
                            useItemStack(toItem, fromStack);

                        }
                    });
                }
            });

        }

        // setup the tool buttons
        setupButtons(studyViewer);

        // layout choose
        function chooseLayout(r,c) {
            var previousUsed = [];
            imageViewer.forEachElement(function(el, vp, i){
                if (!isNaN($(el).data('useStack'))) {
                    previousUsed.push($(el).data('useStack'));
                }
            });

            var type = r +'x'+c;
            imageViewer.setLayout(type);
            initViewports();
            resizeStudyViewer();
            if (previousUsed.length > 0) {
                previousUsed = previousUsed.slice(0, imageViewer.viewports.length);
                var item = 0;
                previousUsed.forEach(function(v){
                    useItemStack(item++, v);
                });
            }
        }
        /*
         * 插入表格
         * @btn:选择触发器,jquery对象
         * @opt:表格选项,{min:[最小列数,最小行数],max:[最大列数,最大行数],insert:确认选择后回调事件}
         */
        var insertTable = function(btn,opt){
            if(!btn){return;}
            this.btn = btn;
            opt = opt || {};
            this.box = null;//弹框
            this.inBox = null;
            this.pickUnLight = null;
            this.pickLight = null;
            this.status = null;
            this.minSize = opt.min || [5,5];//最小列数和行数
            this.maxSize = opt.max || [15,15];//最大列数和行数
            this.insert = opt.insert;//回调
            this.nowSize = [];//当前选择尺寸
            this.isInit = {create:false,bind:false};
            this.bind();
        }
        insertTable.prototype = {
            init : function(){
                if(this.isInit.create){return;}
                this.isInit.create = true;
                var id = 'in_tab_box_'+String(Math.ceil(Math.random() * 100000) + String(new Date().getTime())),
                    html = '<div class="in_tab_box" id="'+id+'">';
                html += 	'<div class="itb_con">';
                html += 		'<div class="itb_picker_unlight"></div>';
                html += 		'<div class="itb_picker_light"></div>';
                html += 	'</div>';
                html += 	'<div class="itb_picker_status"></div>';
                html += '</div>';
                $("body").append(html);
                this.box = $("#"+id);
                this.inBox = this.box.find(".itb_con");
                this.pickAll = this.box.find(".itb_picker_all");
                this.pickUnLight = this.box.find(".itb_picker_unlight");
                this.pickLight = this.box.find(".itb_picker_light");
                this.status = this.box.find(".itb_picker_status");

                this.setBg(this.minSize[0],0);
                this.setBg(this.minSize[1],1);

                this.status.text(0+'列 x '+0+'行');
            },
            bind : function(){
                var T = this,
                    pos,//弹框显示位置
                    m,
                    bPos,//弹框可选区域位置
                    mPos;//鼠标位置
                this.btn.click(function(){
                    if(!T.isInit.create){T.init();}//初始化弹框
                    if(!T.isInit.bind){B();}//初始化事件
                    m = $(this);
                    if(T.box.is(":hidden")){
                        pos = {
                            top:m.offset().top +m.outerHeight(),
                            left:m.offset().left
                        }
                        T.box.css({
                            "top":pos.top,
                            "left":pos.left
                        }).fadeIn(100);
                        bPos = {
                            top : T.inBox.offset().top ,
                            left : T.inBox.offset().left
                        }

                        $(document).bind("click",function(){T.hide();});
                        $('.dropdown-toggle').bind("click.bs.dropdown",function(){T.hide();});
                    }else{
                        T.hide();
                    }
                    return false;
                })
                function B(){
                    T.isInit.bind = true;
                    T.inBox.mousemove(function(e){
                        mPos = {
                            x : e.clientX,
                            y : e.clientY
                        }
                        if(mPos.x < bPos.left || mPos.y < bPos.top){return;}
                        T.nowSize[0] = Math.ceil((mPos.x - bPos.left)/18);//列数
                        T.nowSize[1] = Math.ceil((mPos.y - bPos.top)/18);//行数

                        if(T.nowSize[0]>=T.minSize[0]&&T.nowSize[0]<T.maxSize[0]){
                            T.setBg(T.nowSize[0]+1,0);
                        }else if(T.nowSize[0]<T.minSize[0]){
                            T.setBg(T.minSize[0],0);
                        }else{
                            T.nowSize[0] = T.maxSize[0];
                        }
                        if(T.nowSize[1]>=T.minSize[1]&&T.nowSize[1]<T.maxSize[1]){
                            T.setBg(T.nowSize[1]+1,1);
                        }else if(T.nowSize[1]<T.minSize[1]){
                            T.setBg(T.minSize[1],1);
                        }else{
                            T.nowSize[1] = T.maxSize[1];
                        }

                        T.pickLight.css({
                            "width":T.nowSize[0]+'em',
                            "height":T.nowSize[1]+'em'
                        })
                        T.status.text(T.nowSize[0]+'列 x '+T.nowSize[1]+'行');
                    })
                    //单击确认插入表格
                    T.box.click(function(){
                        if(T.nowSize[0]>0&&T.nowSize[0]<=T.maxSize[0]&&T.nowSize[1]>0&&T.nowSize[1]<=T.maxSize[1]){
                            var rows = T.nowSize[1],
                                cols = T.nowSize[0];
                            chooseLayout(rows,cols);

                            //try{T.insert(rows,cols);}catch(e){}
                        }
                    })
                }
            },
            //调整背景区域
            setBg : function(size,t){
                if(t==0){
                    this.inBox.width(size+'em');
                    this.pickUnLight.width(size+'em');
                }else{
                    this.inBox.height(size+'em');
                    this.pickUnLight.height(size+'em');
                }
            },
            //隐藏弹框
            hide : function(){
                var T = this;
                this.box.fadeOut(100,function(){
                    //重置
                    T.setBg(T.minSize[0],0);
                    T.setBg(T.minSize[1],1);
                    T.pickLight.css({
                        "width":'0',
                        "height":'0'
                    })
                });
            }
        }
        new insertTable($(".insert_table"),{
            min : [4,4],
            max : [20,20],
            insert : function(rows,cols){
                //这里只返回所选行数rows和列数cols,插入后的效果和样式需自定义,以下只是做简单的示例
                //alert('插入了一个'+rows+'行'+cols+'列的表格');
                var html = '<table>';
                for(var i=0;i<rows;i++){
                    html += '<tr>';
                    for(var j=0;j<cols;j++){
                        html += '<td></td>';
                    }
                    html += '</tr>';
                }
                html += '</table>';
                this.btn.siblings("table").remove();
                this.btn.after(html);
            }
        });
        // end layout choose

        // Load the first series into the viewport (?)
        //var stacks = [];
        //var currentStackIndex = 0;
        var seriesIndex = 0;

        // Create a stack object for each series
        console.log(data['series'])
        for(var index = 0;index < data['series'].length ; index++) {
            var series = data['series'][index];
            var stack = {
                seriesDescription: series.description == null ? '没有描述' : series.description,
                stackId: series.SeriesNumber,
                SeriesNumber:series.SeriesNumber,
                imageIds: [],
                seriesIndex: seriesIndex,
                currentImageIdIndex: 0,
                frameRate: series.frameRate
            };
            //console.log('stack',stack);

            // Populate imageIds array with the imageIds from each series
            // For series with frame information, get the image url's by requesting each frame
            if (series.numberOfFrames !== undefined) {
                var numberOfFrames = series.numberOfFrames;
                for (var i = 0; i < numberOfFrames; i++) {
                    var imageId = series.instanceList[0].imageId + "?frame=" + i;
                    if (imageId.substr(0, 4) !== 'http') {
                        imageId = "dicomweb://jarvisframetech.org/images/ClearCanvas/" + imageId;
                    }
                    stack.imageIds.push(imageId);
                }

                // Otherwise, get each instance url
            } else {
                //console.log('series',series);
                series.images.forEach(function(image) {
                    //todo
                    var downloadurl = myurl.replace('http','dicomweb');
                    var imageId =downloadurl + 'test/download/' + image.MD5;
                    imageId = 'http://eye.zspcl.com:20000/'+ image.metadata;
                    stack.imageIds.push(imageId);

                });
            }
            // Move to next series
            seriesIndex++;
            console.log('stack',stack)
            // Add the series stack to the stacks array
            imageViewer.stacks.push(stack);
        }
        // data['series'].forEach(function(series) {
        //     var stack = {
        //         seriesDescription: series.SeriesDescription,
        //         stackId: series.SeriesNumber,
        //         SeriesNumber:series.SeriesNumber,
        //         imageIds: [],
        //         seriesIndex: seriesIndex,
        //         currentImageIdIndex: 0,
        //         frameRate: series.frameRate
        //     };
        //     //console.log('stack',stack);
        //
        //     // Populate imageIds array with the imageIds from each series
        //     // For series with frame information, get the image url's by requesting each frame
        //     if (series.numberOfFrames !== undefined) {
        //         var numberOfFrames = series.numberOfFrames;
        //         for (var i = 0; i < numberOfFrames; i++) {
        //             var imageId = series.instanceList[0].imageId + "?frame=" + i;
        //             if (imageId.substr(0, 4) !== 'http') {
        //                 imageId = "dicomweb://jarvisframetech.org/images/ClearCanvas/" + imageId;
        //             }
        //             stack.imageIds.push(imageId);
        //         }
        //
        //         // Otherwise, get each instance url
        //     } else {
        //         //console.log('series',series);
        //         series.Instances.forEach(function(image) {
        //
        //             var downloadurl = myurl.replace('http','dicomweb');
        //             var imageId =downloadurl + 'test/download/' + image.MD5;
        //             stack.imageIds.push(imageId);
        //
        //         });
        //     }
        //     // Move to next series
        //     seriesIndex++;
        //
        //     // Add the series stack to the stacks array
        //     imageViewer.stacks.push(stack);
        // });

        // Resize the parent div of the viewport to fit the screen
        var imageViewerElement = $(studyViewer).find('.imageViewer')[0];
        var viewportWrapper = $(imageViewerElement).find('.viewportWrapper')[0];
        var parentDiv = $(studyViewer).find('.viewer')[0];

        //viewportWrapper.style.width = (parentDiv.style.width - 10) + "px";
        //viewportWrapper.style.height = (window.innerHeight - 150) + "px";

        var studyRow = $(studyViewer).find('.studyRow')[0];
        var width = $(studyRow).width();

        //$(parentDiv).width(width - 170);
        //viewportWrapper.style.width = (parentDiv.style.width - 10) + "px";
        //viewportWrapper.style.height = (window.innerHeight - 150) + "px";

        // Get the viewport elements
        var element = $(studyViewer).find('.viewport')[0];

        // Image enable the dicomImage element
        initViewports();
        //jarvisframe.enable(element);

        // Get series list from the series thumbnails (?)
        var seriesList = $(studyViewer).find('.thumbnails')[0];
        imageViewer.stacks.forEach(function(stack, stackIndex) {

            // Create series thumbnail item
            var seriesEntry = '<a class="list-group-item" + ' +
                'oncontextmenu="return false"' +
                'unselectable="on"' +
                'onselectstart="return false;"' +
                'onmousedown="return false;">' +
                '<div class="csthumbnail"' +
                'oncontextmenu="return false"' +
                'unselectable="on"' +
                'onselectstart="return false;"' +
                'onmousedown="return false;"><div class="overlay" style="left:3px; top:0px">'+ imageViewer.stacks[stack.seriesIndex].imageIds.length +'</div></div>' +
                "<div class='text-center small'>" + stack.seriesDescription + '</div></a>';

            // Add to series list
            var seriesElement = $(seriesEntry).appendTo(seriesList);

            // Find thumbnail
            var thumbnail = $(seriesElement).find('div')[0];

            // Enable jarvisframe on the thumbnail
            jarvisframe.enable(thumbnail);

            // Have jarvisframe load the thumbnail image
            console.log('显示缩略图',imageViewer.stacks[stack.seriesIndex].imageIds[0])
            jarvisframe.loadAndCacheImage(imageViewer.stacks[stack.seriesIndex].imageIds[0]).then(function(image) {
                // Make the first thumbnail active
                if (stack.seriesIndex === 0) {
                    $(seriesElement).addClass('active');
                }
                // Display the image 显示缩略图
                console.log('显示缩略图',thumbnail, image)
                jarvisframe.displayImage(thumbnail, image);
                // $(seriesElement).draggable({helper: "clone"});
            });

            // Handle thumbnail click
            $(seriesElement).on('click touchstart', function() {
                useItemStack(0, stackIndex);
            }).data('stack', stackIndex);
        });

        function useItemStack(item, stack) {
            var imageId = imageViewer.stacks[stack].imageIds[0], element = imageViewer.getElement(item);
            if ($(element).data('waiting')) {
                imageViewer.viewports[item].find('.overlay-text').remove();
                $(element).data('waiting', false);
            }
            $(element).data('useStack', stack);

            displayThumbnail(seriesList, $(seriesList).find('.list-group-item')[stack], element, imageViewer.stacks[stack], function(el, stack){
                if (!$(el).data('setup')) {
                    setupViewport(el, stack, this);
                    setupViewportOverlays(el, data);
                    $(el).data('setup', true);
                }
            });


            /*    jarvisframe.loadAndCacheImage(imageId).then(function(image){
             setupViewport(element, imageViewer.stacks[stack], image);
             setupViewportOverlays(element, data);
             });*/
        }
        // Resize study viewer
        function resizeStudyViewer() {
            var studyRow = $(studyViewer).find('.studyContainer')[0];
            var height = $(studyRow).height();
            var width = $(studyRow).width();
            //console.log($(studyRow).innerWidth(),$(studyRow).outerWidth(),$(studyRow).width());
            $(seriesList).height("100%");
            $(parentDiv).width(width - $(studyViewer).find('.thumbnailSelector:eq(0)').width());
            $(parentDiv).css({height : '100%'});
            $(imageViewerElement).css({height : $(parentDiv).height() - $(parentDiv).find('.text-center:eq(0)').height()});

            imageViewer.forEachElement(function(el, vp) {
                jarvisframe.resize(el, true);

                if ($(el).data('waiting')) {
                    var ol = vp.find('.overlay-text');
                    if (ol.length < 1) {
                        ol = $('<div class="overlay overlay-text">请拖拽图像到图像显示区.</div>').appendTo(vp);
                    }
                    var ow = vp.width() / 2, oh = vp.height() / 2;
                    ol.css({top : oh, left : ow - (ol.width() / 2)});
                }
            });
            //增加选中图像边框颜色
            $('.viewportWrapper').click(function(event){
                $(this).addClass("viewportWrapperSelect");
                $(this).siblings().removeClass("viewportWrapperSelect");
            })
        }
        // Call resize viewer on window resize
        $(window).resize(function() {
            resizeStudyViewer();
        });
        resizeStudyViewer();
        if (imageViewer.isSingle())
            useItemStack(0, 0);

    }
    // $.getJSON(studyurl, function (data) {
    //     doFunc2(data)
    // });
    req(REPOET_QUERY,{studyId:'19664'},data => {
        doFunc2(data)
        console.log('success',data);
    },err => {
        console.log('err',data);
    })
    // $.ajax({
    //     url: ' http://139.199.119.129:20001/query' ,
    //     type: 'POST',
    //     data: {studyId:'19664'},
    //     async: true,
    //     cache: false,
    //     contentType: false,
    //     processData: false,
    //     success: function (returndata) {
    //         console.log('success2',returndata);
    //         doFunc2(data);
    //     },
    //     error: function (returndata) {
    //         console.log('err2',returndata);
    //     }
    // });
}
